package com.zxd.interview.eightthread.threadobjectclasscommonmethod;

import com.zxd.interview.util.date.DateHelper;

import java.util.concurrent.TimeUnit;

/**
 * sleep 被中断
 * 每隔一秒钟打印一下当前的时间
 * 1. sleep 响应中断状态
 * 2. 清除中断状态，注意此时try/catch的位置很关键
 * <p>
 * 扩展，为什么更推荐使用 TimeUnit.SECONDS.sleep(5);?
 * 因为传统的Thread.sleep 如果传入一个负数，会抛出异常
 * TimeUnit.SECONDS.sleep(5); 这种写法则会检查timeout值是否>0，如果不是则什么都不做
 *
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.threadobjectclasscommonmethod
 * @Description : sleep 被中断
 * @Create on : 2023/3/15 13:50
 **/
public class SleepInterrupted implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new SleepInterrupted());
        thread.start();
        TimeUnit.SECONDS.sleep(5);
        thread.interrupt();
        Thread.sleep(11);
    }


    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(DateHelper.getNowByNew(DateHelper.yyyyMMdd_hhmmss));
                // 更为优雅的写法
                TimeUnit.SECONDS.sleep(1);
            }
            // try/catch 在循环内部，清除中断标志，但是程序依然会继续运行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }/**
     正确的响应中断应该是下面的输出结果：
     2023-03-15 13:57:38
     2023-03-15 13:57:39
     2023-03-15 13:57:40
     2023-03-15 13:57:41
     2023-03-15 13:57:42
     java.lang.InterruptedException: sleep interrupted
     at java.base/java.lang.Thread.sleep(Native Method)
     at java.base/java.lang.Thread.sleep(Thread.java:334)
     at java.base/java.util.concurrent.TimeUnit.sleep(TimeUnit.java:446)
     at com.zxd.interview.eightthread.threadobjectclasscommonmethod.SleepInterrupted.ru

     循环内部try/catch 虽然响应了中断，但是子线程依然在运行
     2023-03-15 13:55:24
     2023-03-15 13:55:25
     2023-03-15 13:55:26
     2023-03-15 13:55:27
     2023-03-15 13:55:28
     java.lang.InterruptedException: sleep interrupted
     at java.base/java.lang.Thread.sleep(Native Method)
     at java.base/java.lang.Thread.sleep(Thread.java:334)
     at java.base/java.util.concurrent.TimeUnit.sleep(TimeUnit.java:446)
     at com.zxd.interview.eightthread.threadobjectclasscommonmethod.SleepInterrupted.run(SleepInterrupted.java:32)
     at java.base/java.lang.Thread.run(Thread.java:829)
     2023-03-15 13:55:29
     2023-03-15 13:55:30
     2023-03-15 13:55:31
     2023-03-15 13:55:32
     2023-03-15 13:55:33
     */
}
